<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Account\Back;

use AuctionCore\System\AuctionException;
use AuctionCore\Account\User;

/**
 * 后台员工帐号功能类
 * @author       爱民
 */
class Employee extends User
{

    /**
     * 用户名
     * @var      String
     */
    protected $user_name;

    /**
     * 授权管理功能类
     * @var int
     */
    protected $auth_object;

    /**
     * 构造,初始化后台auth对象
     * @param  String $user_name 后台登录用户名
     * @return void
     */
    public function __construct($account_name)
    {
        $b_auth = new \AuctionCore\Account\Back\Auth();
        $this->auth_object = $b_auth;
        if (is_numeric($account_name)) {
            $info = self::user_info_id($account_name);
            $this->user_name = $info['username'];
        } else {
            $this->user_name = $account_name;
        }
    }

    /**
     * 创建后台员工
     * @param array $info [用户名，密码,昵称,手机号,....]
     * @return integer user_id
     */
    public static function create_emp($info)
    {

        $fu = new Employee($info['username']);
        $is_exists = $fu->user_info();
        if (!empty($is_exists)) {
            AuctionException::make_throw('300005');
        }

        if (empty($info['username'])) {
            AuctionException::make_throw('300001');
        }
        if (empty($info['passwd'])) {
            AuctionException::make_throw('300002');
        }

        $b_auth = new \AuctionCore\Account\Back\Auth();
        $auth_db_cfg = $b_auth->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);

        $info['passwd'] = md5($info['passwd']);
        $now = date("Y-m-d H:i:s", time());
        $info['createtime'] = $now;
        $info['status'] = 0;
        $user_id = $m->add($info);
        if ($user_id && $info['group_id']) {
            //加入组
            $bu = new Employee($user_id);
            $bu->set_group($info['group_id']);
        }
        return $user_id;
    }

    private function _getModel()
    {
        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);
        return $m;
    }

    /**
     * 配合属性“用户名”，修改密码
     * 返回:true/false
     *
     *
     * @param    String $new_pwd 新密码
     * @return   boolean
     */
    public function change_password($new_pwd)
    {

        if (!$this->user_name) {
            AuctionException::make_throw('300003');
        }
        if (empty($new_pwd)) {
            AuctionException::make_throw('300004');
        }

        $m = $this->_getModel();
        $sets = array('passwd' => md5($new_pwd));
        $ok = $m->where(array('username' => $this->user_name))->save($sets);
        return $ok;
    }

    //更新员工信息 [group_id:员工所属组，username:用户名.......等 等 ]
    public function update($info)
    {
        $detail = $this->user_info();
        //$old_group_id = $detail['group_info'][0]['id'];
        $old_depart_id = $detail['depart_id'];
        if ($old_depart_id != $info['depart_id']) {
            $info['is_head'] = 0;
        }
//        if ($info['group_id'] && $old_group_id != $info['group_id']) {
//            $this->exgraft_group($old_group_id);
//            $this->set_group($info['group_id']);
//        }
        $m = $this->_getModel();
        return $m->where(['username' => $this->user_name])->save($info);
    }


    /**
     * 检查密码是否正确，检查启用状态，登录或修改密码使用。
     * 返回：用户信息
     * @param    String $pwd 帐号密码
     * @return   Object
     */
    public function check_pwd($pwd)
    {
        $m = $this->_getModel();
        $info = $m->where(array('username' => $this->user_name))->find();
        if ($info['passwd'] == md5($pwd)) {
            return $info;
        } else {
            return false;
        }
    }

    public function get_user_branch($info)
    {
        $map = array();
        $map['e.emp_id'] = $info['emp_id'];
        $user_branch = M('employee')->alias('e')->field('e.*,group_concat(bc.city_code) as `bc_code`,group_concat(ac.name) as `bc_name`,d.is_branch_department,d.branch_id')
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "depart d ON d.id = e.depart_id")
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "branch_city bc ON bc.branch_id = d.branch_id")
            ->join(C('DB_PREFIX') . "apply_city ac ON ac.code = bc.city_code")
            ->where($map)->find();
        if (!$user_branch) {
            return false;
        }
        if ($user_branch['is_branch_department'] == 0) {
            $info['bc_code'] = array();
            $info['is_branch_department'] = $user_branch['is_branch_department'];
            $info['branch_id'] = $user_branch['branch_id'];
        } else {
            $info['bc_code'] = explode(',', $user_branch['bc_code']);
            $info['bc_name'] = explode(',', $user_branch['bc_name']);
            $info['is_branch_department'] = $user_branch['is_branch_department'];
            $info['branch_id'] = $user_branch['branch_id'];
        }
        return $info;
    }

    /**
     * 用户详细
     * @return   Object
     */
    public function user_info()
    {
        $m = $this->_getModel();
        $user_name = $this->user_name;
        $info = $m->where("username='{$user_name}'")->find();

        if ($info) {
            $info['group_info'] = M()->query("SELECT g.* FROM au_emp_group_access ac LEFT JOIN au_auth_employee_group g ON ac.id=g.id WHERE ac.emp_id='{$info['emp_id']}';");
        }
        return $info;
    }

    /**
     * 用户详细BY id
     * @param $id int 用户ID
     * @return   Object
     */
    public static function user_info_id($id)
    {
        $m = M("employee");
        $info = $m->find($id);
        return $info;
    }

    /**
     * 员工姓名找id
     * @param $real_name string 员工姓名
     * @return int
     */
    public static function user_info_rela_name($real_name)
    {
        $m = M("employee");
        $info = $m->where("real_name='$real_name'")->getField("emp_id");
        return $info;
    }

    /**
     * 启用帐号
     * @return   void
     */
    public function enable()
    {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '0'));
    }

    /**
     * 禁用帐号
     * @return   void
     */
    public function disable()
    {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '1'));
    }

    //逻辑删除
    public function del()
    {
        $m = $this->_getModel();
        $ok = $m->where(array('username' => $this->user_name))->save(array('status' => '-1'));
    }

    /**
     * 设置员工所属分组
     * @param    int $group_id 组id
     * @return   int
     */
    public function set_group($group_id)
    {
        $emp_info = $this->user_info();
        $group_users = array('emp_id' => $emp_info['emp_id'], 'id' => $group_id);

        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_GROUP_ACCESS"]);
        $m->add($group_users);
    }

    /**
     * 员工移出所属分组
     * @param    int $group_id 组id
     * @return   int
     */
    public function exgraft_group($group_id)
    {
        $user_info = $this->user_info();
        $auth_db_cfg = $this->auth_object->get_config();
        $m = M($auth_db_cfg["AUTH_GROUP_ACCESS"]);
        $where = "emp_id='{$user_info['emp_id']}' and id='{$group_id}'";
        $ok = $m->where($where)->delete();
        return $ok;
    }

    /**
     * 添加用户和权限组关系
     *
     * @param $data 用户权限组数据
     * @return mixed
     */
    public function addEmpGroupRelation($data)
    {
        $auth_db_cfg = $this->auth_object->get_config();
        $result = M($auth_db_cfg["AUTH_GROUP_ACCESS"])->addAll($data);
        return $result;
    }

    /**
     * 删除用户和权限组关系
     *
     * @param $data 用户权限组数据
     * @return mixed
     */
    public function delEmpGroupRelation($data)
    {
        $auth_db_cfg = $this->auth_object->get_config();
        $result = M($auth_db_cfg["AUTH_GROUP_ACCESS"])->where($data)->delete();
        return $result;
    }


    /**
     * 获取用户分组
     * @return   Object
     */
    public function get_groups()
    {
        $user_info = $this->user_info();
        $uid = $user_info['emp_id'];
        $prefix = C('DB_PREFIX');
        $rows = M()->query("SELECT ac.emp_id,g.id group_id ,g.* FROM `{$prefix}emp_group_access` ac LEFT JOIN {$prefix}auth_employee_group g  ON ac.id = g.id WHERE ac.emp_id = '{$uid}'");
        return $rows;
    }

    /**
     * 获取部门
     * @param $emp_id
     * @return array
     */
    public static function get_emp_group($emp_id)
    {
        $map = array("emp_id" => $emp_id);
        $arr = M('emp_group_access')->where($map)->select();
        return $arr;
    }

    /**
     * 删除用户
     * @param string $user_name 用户名
     * @return bool
     */
    public static function remove_emp($user_name)
    {

        if (empty($user_name)) {
            AuctionException::make_throw('300006');
        }

        $b_auth = new \AuctionCore\Account\Back\Auth();
        $e = new self($user_name);
        $info = $e->user_info();
        $emp_id = $info['emp_id'];

        $auth_db_cfg = $b_auth->get_config();
        $m = M($auth_db_cfg["AUTH_USER"]);
        $ok = $m->where("username='" . $user_name . "'")->delete();

        $m = M($auth_db_cfg["GROUP_ACCESS"]);
        $ok = $m->where("emp_id='" . $emp_id . "'")->delete();

        return $ok;
    }

    /**
     * 检查权限
     * @param rule_names string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check_auth($rule_names)
    {
        $user_info = $this->user_info();
        $uid = $user_info['emp_id'];
        $ok = $this->auth_object->check($rule_names, $uid);

        return $ok;
    }

    /**
     * 检查员工权限
     */
    public static function check_emp_auth($rule_names, $uid)
    {
        $b_auth = new \AuctionCore\Account\Back\Auth();
        return $b_auth->check($rule_names, $uid);
    }

    /**
     * 找到员工对应所有权限
     */
    public function get_emp_auth()
    {
        $user_info = $this->user_info();
        $uid = $user_info['emp_id'];
        $ok = $this->auth_object->get_auth_list($uid);
        return $ok;
    }

    /**
     * 通过组id获取雇员
     * @param int $group_id
     * @return multitype:|unknown
     */
    public static function get_emp_by_group_or_store($group_id, $store = 0)
    {
        if ((int)$group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        $map['d.branch_id'] = ['gt', 0];
        $map['g.id'] = array('eq', $group_id);
        if (intval($store) > 0) {
            $map['e.store'] = array('eq', $store);
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("d.branch_id,e.emp_id,e.real_name")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->where($map)->select();
        return $list;
    }

    /**
     * 通过分公司id 角色id 获取对应人员
     */
    public static function get_branch_emp($group_id, $branch_id = 0)
    {
        if ((int)$group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        $map['g.id'] = array('eq', $group_id);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("d.branch_id,e.emp_id,e.real_name,e.mobile")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->where($map)->select();
        return $list;
    }


    /**
     * 通过分公司id 角色id 获取对应人员(维护人 开发人)
     */
    public static function getBranchEmpForSpecial($group_id, $branch_id = 0)
    {
        if ((int)$group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        $map['eir.identity_id'] = array('eq', $group_id);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("d.branch_id,e.emp_id,e.real_name,e.mobile,r.region_name")
            ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->join("LEFT JOIN {$prefix}region_maintain rm ON rm.maintain_id = e.emp_id")
            ->join("LEFT JOIN {$prefix}region r ON r.rid = rm.region_id")
            ->where($map)->select();
        return $list;
    }

    /**
     * 通过分公司id 角色id 获取对应人员(未绑定片区)
     */
    // public static function get_branch_emp_not_region($group_id, $branch_id = 0)
    // {
    //     if ((int)$group_id < 1) {
    //         return array();
    //     }
    //     $map = array();
    //     $map['e.status'] = array('eq', 0); //状态正常用户
    //     if (intval($branch_id) > 0) {
    //         $map['d.branch_id'] = array('eq', $branch_id);
    //     }
    //     $map['eir.identity_id'] = array('eq', $group_id);
    //     $map['rm.region_id'] = array('exp','is NULL');
    //     $prefix = C('DB_PREFIX');
    //     $list = M('employee')->alias("e")->field("d.branch_id,e.emp_id,e.real_name,e.mobile")
    //         ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
    //         ->join("{$prefix}depart d ON e.depart_id = d.id")
    //         ->join("LEFT JOIN {$prefix}region_maintain rm ON rm.maintain_id = e.emp_id")
    //         ->where($map)->select();
    //     return $list;
    // }

    //通过分公司id 角色id 获取分公司对应人员部门id
    public static function get_branch_depart($group_id, $branch_id = 0)
    {
        if ((int)$group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        $map['g.id'] = array('eq', $group_id);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field('group_concat(DISTINCT e.depart_id) as `all_depart`')
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->where($map)->find();
        return $list;
    }

    /**
     * 通过角色分组id 部门id 获取对应人员
     */
    public static function get_depart_emp($group_id, $depart_id = 0)
    {
        if ((int)$group_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($depart_id) > 0) {
            $map['e.depart_id'] = array('eq', $depart_id);
        }
        $map['g.id'] = array('eq', $group_id);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }


    /**
     * 通过部门Id,组Id获取雇员
     * @param int $depart_id 部门ID
     * @param int $group_id 组ID
     */
    public static function get_emp_by_group_and_branch($depart_id, $group_id)
    {
        if ((int)$group_id < 1 || (int)$depart_id < 1) {
            return array();
        }
        $map = array();
        $map['e.status'] = ['eq', 0];
        $map['e.depart_id'] = ['eq', $depart_id];
        $map['g.id'] = ['eq', $group_id];
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    /**
     * 分公司Id,组Id获取雇员
     * @param int $branch_id 部门ID
     * @param int $group_id 组ID
     * @return array list
     */
    public static function emp_branch_group($branch_id, $group_id)
    {
        $map = array();
        $map['e.status'] = ['eq', 0];
        if ($branch_id > 0) {  //非总部
            $list = M("depart")->where("branch_id=" . $branch_id)->select();
            $departments = array();
            foreach ($list as $k => $item) {
                $departments[] = $item['id'];
            }
            if (!empty($departments)) {
                $map['e.depart_id'] = ['in', $departments];
            }
        }
        $map['g.id'] = ['eq', $group_id];
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name,e.mobile,e.username")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    /**
     *
     * @param $store
     * @param int $group_id
     * @return array
     */
    public static function get_emp_by_store_group($store, $group_id = 0)
    {
        if ((int)$store < 1) {
            return array();
        }
        $map = array();
        $map['e.store'] = array('eq', (int)$store);
        if ((int)$group_id > 1) {
            $map['g.id'] = array('eq', (int)$group_id);
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name")
            ->join("LEFT JOIN {$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    /**
     * 获取所有员工
     * @return mixed
     */
    public static function get_all()
    {
        return M('employee')->select();
    }

    /**
     * 重置密码
     */
    public function restPwd()
    {
        $new_pwd['passwd'] = md5('123456');
        $ok = M('employee')->where(array('username' => $this->user_name))->save($new_pwd);
        return $ok;
    }

    public static function isPhoneExist($phone)
    {
        return M('employee')->where(['mobile' => $phone])->find();
    }

    /**
     * 获取员工对应分公司id
     */
    public static function get_emp_branch_id($emp_id)
    {
        $prefix = C('DB_PREFIX');
        $where = [];
        $where['e.emp_id'] = $emp_id;
        $where['e.status'] = ['eq', 0];
        $emp_info = M('employee')->alias('e')
            ->join($prefix . "depart as d ON d.id = e.depart_id")->where($where)->find();
        return $emp_info['branch_id'];
    }

    //对应分公司下面维护人（不在当前片区）
    public static function getNotInRegionEmpInfo($branch_id, $rid)
    {
        $map = array();
        $map['eir.identity_id'] = array('eq', 2); //维护人
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        if (intval($rid) > 0) {
            $map['rm.region_id'] = array(array('neq', $rid), array('exp', 'is NULL'), 'or');
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name,username,rm.region_id")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
            ->join("LEFT join {$prefix}region_maintain rm ON rm.maintain_id = e.emp_id")
            ->where($map)->select();
        return $list;
    }

    //找到当前片区下维护人

    public static function getInRegionMaintain($rid)
    {
        $map = array();
        $map['eir.identity_id'] = array('eq', 2); //维护人
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($rid) > 0) {
            $map['rm.region_id'] = array('eq', $rid);
        }
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name,e.username")
            ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
            ->join("{$prefix}region_maintain rm ON rm.maintain_id = e.emp_id")
            ->where($map)->select();
        return $list;
    }

    //对应分公司下面评估师(不包含已经绑定关系评估师)

    public static function getNotInFoursAppraiser($branch_id, $emp_ids = array())
    {
        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        if (!empty($emp_ids)) {
            $map['e.emp_id'] = array('not in', $emp_ids);
        }
        $group_id = C('APPRAISER.0');
        $map['g.id'] = array('eq', $group_id);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("e.emp_id,e.real_name,e.username")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->join("{$prefix}emp_group_access g ON e.emp_id = g.emp_id")
            ->where($map)->select();
        return $list;
    }

    //通过手机号找员工id
    public static function getEmpIdByMobile($mobile)
    {
        $map = [];
        $map['mobile'] = ['eq', $mobile];
        $empInfos = M('employee')->where($map)->select();
        return array_column($empInfos, 'emp_id');
    }

    //通过员工名称找员工id
    public static function getEmpIdByName($name)
    {
        $map = [];
        $map['real_name'] = ['eq', $name];
        $map['status'] = ['egt', 0];
        $empInfos = M('employee')->where($map)->select();
        return array_column($empInfos, 'emp_id');
    }

    /**
     * 通过分公司id 获取对应角色的人员
     */
    public static function getBranchRoleEmp($branch_id, $flag)
    {

        $map = array();
        $map['e.status'] = array('eq', 0); //状态正常用户
        if (intval($branch_id) > 0) {
            $map['d.branch_id'] = array('eq', $branch_id);
        }
        $map['eir.identity_id'] = array('eq', $flag);
        $prefix = C('DB_PREFIX');
        $list = M('employee')->alias("e")->field("d.branch_id,e.emp_id,e.real_name,e.mobile")
            ->join("{$prefix}depart d ON e.depart_id = d.id")
            ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
            ->where($map)->select();
        return $list;
    }

    //判断是否是4s店维护人
    public function isFourStoreMaintainOrDeveloper($identity)
    {
        $map = array();
        $map['eir.identity_id'] = array('eq', $identity);
        $map['e.username'] = array('eq', $this->user_name);
        $map['e.status'] = ['eq', 0];
        $prefix = C('DB_PREFIX');
        $empInfo = M('employee')->alias("e")->field("e.emp_id")
            ->join("{$prefix}emp_identity_relation eir ON eir.emp_id = e.emp_id")
            ->where($map)->find();
        if (!empty($empInfo))
            return true;
        else
            return false;
    }

    //找到对应人员片区
    public function getRegionByEmp()
    {
        $map = array();
        $map['e.username'] = array('eq', $this->user_name);
        $map['e.status'] = ['eq', 0];
        $prefix = C('DB_PREFIX');
        $regionInfo = M('region_maintain')->alias("rm")->field("rm.region_id,r.region_name")
            ->join("{$prefix}employee e ON e.emp_id = rm.maintain_id")
            ->join("{$prefix}region r ON r.rid = rm.region_id")
            ->where($map)->find();
        return $regionInfo;
    }


    /**
     * 通过权限组编号，得到权限组信息
     *
     * @param $groupId 权限组编号
     * @return mixed
     */
    public static function getGroupByGroupId($groupId)
    {
        return M('auth_employee_group')->where(['id' => $groupId])->find();
    }
}   


